<!--
 * @Descripttion: (报警记录表/cks_work_rec)
 * @Author: (admin)
 * @Date: (2025-7-23)
-->
<template>
  <div>
    <!-- 查询表单 -->
    <el-form style="margin-left: 5px;margin-top: 10px;" :model="queryParams" label-position="right" :inline="true"
      ref="queryRef" v-show="showSearch">

      <el-form-item :label="$t('review.cksworkrecordPage.page.productionLineCode')" prop="lineCode">
        <el-select clearable style="width: 260px" v-model="queryParams.lineCode"
          @change="queryParams.stationCode = ''; state.options.workstationCodeOptions = state.options.productionLineList.find(item => item.lineCode === $event)?.workStation || []"
          :placeholder="$t('review.cksworkrecordPage.page.productionLineCodeInput')">
          <el-option v-for="item in options.productionLineOptions" :key="item.dictValue" :label="item.dictLabel"
            :value="item.dictValue" />
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('review.cksworkrecordPage.page.stationCode')" prop="stationCode">
        <el-select clearable style="width: 260px" v-model="queryParams.stationCode"
          :placeholder="$t('review.cksworkrecordPage.page.stationCodeInput')">
          <el-option v-for="item in options.workstationCodeOptions" :key="item.WorkstationCode"
            :label="item.WorkstationCode" :value="item.WorkstationCode" />
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('review.cksworkrecordPage.page.primaryCode')" prop="primaryCode">
        <el-input v-model="queryParams.primaryCode" :placeholder="$t('review.cksworkrecordPage.page.primaryCodeInput')"
          clearable @keyup.enter="handleQuery" style="width: 200px" />
      </el-form-item>

      <el-form-item :label="$t('review.cksworkrecordPage.page.createdTime')" prop="dateRange">
        <el-date-picker style="width: 360px" v-model="queryParams.dateRange" type="datetimerange"
          :default-time="defaultTime" :shortcuts="shortcuts" value-format="YYYY-MM-DD HH:mm:ss" range-separator="-" />
      </el-form-item>

      <el-form-item>
        <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['cksworkrecord:export']">{{
          $t('btn.export') }}</el-button>
        <el-button type="danger" icon="RefreshLeft" @click="resetWork" v-hasPermi="['cksworkrecord:rework']">{{
          $t('review.cksworkrecordPage.btn.rework') }}</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="15" class="mb10">
      <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar> -->
    </el-row>

    <!-- 数据表格 -->
    <el-table :data="dataList" v-loading="loading" ref="table" border header-cell-class-name="el-table-header-cell"
      highlight-current-row style="width: 100%">
      <el-table-column type="selection" width="40" :selectable="selectable" />

      <el-table-column v-for="col in columns.filter(o => o.visible)" :key="col.prop" :prop="col.prop"
        :label="$t('review.cksworkrecordPage.tableColumns.' + col.prop)" align="center" :width="col.width || 'auto'"
        :show-overflow-tooltip="true">

        <!-- dbBlockRemark -->
        <template #default="scope" v-if="col.prop == 'dbBlockRemark'">
          <span v-if="scope.row.dbBlockRemark">{{ scope.row.dbBlockRemark }}</span>
          <span v-else>-</span>
        </template>

        <!-- 加工结果 -->
        <template #default="scope" v-if="col.prop == 'result'">
          <el-tag v-if="scope.row.result !== null" :type="scope.row.result === 1 ? 'success' : 'danger'"
            disable-transitions>
            <div style="display: flex;align-items: center;justify-items: center;">
              <span>{{ scope.row.result === 1 ? $t('review.cksworkrecordPage.formDialog.ok') :
                $t('review.cksworkrecordPage.formDialog.ng') }}</span>
            </div>
          </el-tag>
          <span v-else>-</span>
        </template>
        <!-- 是否有效 -->
        <template #default="scope" v-else-if="col.prop == 'nullity'">
          <el-icon v-if="scope.row.nullity === true" style="color: green;">
            <CircleCheckFilled />
          </el-icon>
          <el-icon v-else-if="scope.row.nullity === false" style="color: red;">
            <CircleCloseFilled />
          </el-icon>
          <span v-else>-</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </div>
</template>

<script setup name="cksworkrecord">
import { listCksWorkRecord, workStationReWork } from '@/api/business/cksworkrecord.js'
import { queryProductionLinePlcInfo } from '@/api/business/plcconfig.js'
import dayjs from 'dayjs'

const { proxy } = getCurrentInstance()
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])
const loading = ref(false)
const showSearch = ref(true)
const today = dayjs()
const table = ref(null)

// 时间范围快捷选项
const shortcuts = [
  {
    text: proxy.$t('common.today'),
    value: () => {
      const start = new Date().setHours(0, 0, 0, 0)
      const end = new Date().setHours(23, 59, 59, 999)
      return [start, end]
    },
  },
  {
    text: proxy.$t('common.thisWeek'),
    value: () => {
      const start = new Date()
      const end = new Date().setHours(23, 59, 59, 999)
      start.setHours(0, 0, 0, 0)
      start.setDate(start.getDate() - 7)
      return [start, end]
    },
  },
  {
    text: proxy.$t('common.thisMonth'),
    value: () => {
      const start = new Date()
      const end = new Date().setHours(23, 59, 59, 999)
      start.setHours(0, 0, 0, 0)
      start.setMonth(start.getMonth() - 1)
      return [start, end]
    },
  },
  {
    text: proxy.$t('common.last3Month'),
    value: () => {
      const start = new Date()
      const end = new Date().setHours(23, 59, 59, 999)
      start.setHours(0, 0, 0, 0)
      start.setMonth(start.getMonth() - 3)
      return [start, end]
    },
  },
]

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  lineCode: '',
  stationCode: '',
  primaryCode: '',
  dateRange: [today.startOf('day').format('YYYY-MM-DD HH:mm:ss'), today.endOf('day').format('YYYY-MM-DD HH:mm:ss')],
})

const columns = ref([
  { visible: true, prop: 'id', label: proxy.$t('review.cksworkrecordPage.tableColumns.id'), width: '140' },
  { visible: true, prop: 'productionLineCode', label: proxy.$t('review.cksworkrecordPage.tableColumns.productionLineCode'), width: '150' },
  { visible: true, prop: 'stationCode', label: proxy.$t('review.cksworkrecordPage.tableColumns.stationCode'), width: '0' },
  { visible: true, prop: 'primaryCode', label: proxy.$t('review.cksworkrecordPage.tableColumns.primaryCode') },
  { visible: true, prop: 'dbBlockRemark', label: proxy.$t('review.cksworkrecordPage.tableColumns.dbBlockRemark') },
  { visible: true, prop: 'moveInTime', label: proxy.$t('review.cksworkrecordPage.tableColumns.moveInTime'), width: '' },
  { visible: false, prop: 'productionStartTime', label: proxy.$t('review.cksworkrecordPage.tableColumns.productionStartTime'), width: '180' },
  { visible: false, prop: 'productionEndTime', label: proxy.$t('review.cksworkrecordPage.tableColumns.productionEndTime'), width: '180' },
  { visible: true, prop: 'moveOutTime', label: proxy.$t('review.cksworkrecordPage.tableColumns.moveOutTime'), width: '' },
  { visible: false, prop: 'createdTime', label: proxy.$t('review.cksworkrecordPage.tableColumns.createdTime'), width: '180' },
  { visible: true, prop: 'result', label: proxy.$t('review.cksworkrecordPage.tableColumns.result'), width: '' },
  { visible: true, prop: 'nullity', label: proxy.$t('review.cksworkrecordPage.tableColumns.nullity'), width: '' },
])

const total = ref(0)
const dataList = ref([])

const state = reactive({
  options: {
    // 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
    productionLineList: [],
    // 产线
    productionLineOptions: [],
    // workstation code
    workstationCodeOptions: [],
  }
});
const { options } = toRefs(state)

// 选择行的可选性函数
const selectable = (row) => dataList.value.find(o => o.nullity === true && o.id === row.id) ? true : false

function getList() {
  loading.value = true
  const formBody = JSON.parse(JSON.stringify(queryParams));
  proxy.addDateRange(formBody, queryParams.dateRange);
  delete formBody.dateRange;
  listCksWorkRecord(formBody).then(res => {
    const { code, data } = res
    if (code === 200) {
      dataList.value = data.result
      total.value = data.totalNum
    }
    loading.value = false
  })
}

function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

function handleExport() {
  proxy.$modal.msg(proxy.$t('review.cksworkrecordPage.operateTips.exportTodo'));
}

function resetWork() {
  if (proxy.$refs.table) {
    const selectedRows = proxy.$refs.table.getSelectionRows();
    if (selectedRows.length === 0) {
      proxy.$modal.msgWarning(proxy.$t('review.cksworkrecordPage.operateTips.reworkSelectTip'), 'warning');
      return;
    }
    proxy
    .$confirm(proxy.$t('review.cksworkrecordPage.operateTips.reworkConfirm',{ count: selectedRows.length }),proxy.$t("common.systemTips"), {
      confirmButtonText: proxy.$t('common.ok'),
      cancelButtonText: proxy.$t('common.cancel'),
      type: 'warning'
    }).then(() => {
      workStationReWork(selectedRows).then(res => {
        const { code, data } = res
        if (code === 200 && data.isSuccess) {
          getList();
          proxy.$modal.msgSuccess(proxy.$t('common.operateSuccess'))
        } else {
          proxy.$modal.msgError(proxy.$t('review.cksworkrecordPage.operateTips.reworkFail', { errorMsg: data.errorMsg }));
        }
      })
    }).catch(() => { });
  }
}


queryProductionLinePlcInfo().then(res => {
  const { code, data } = res
  if (code == 200) {
    state.options.productionLineList = data;
    state.options.productionLineOptions = data.map(item => ({
      dictLabel: item.lineCode,
      dictValue: item.lineCode
    }));
  }
})

handleQuery()

</script>